package com.yuyou.tas.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.tas.admin.mapper.AuthRoleMapper;
import com.yuyou.tas.admin.mapper.AuthUserMapper;
import com.yuyou.tas.admin.mapper.AuthUserRoleRelationMapper;
import com.yuyou.tas.admin.mapper.AuthUserSectionMapper;
import com.yuyou.tas.admin.mapper.AuthUserSubjectMapper;
import com.yuyou.tas.admin.service.IAuthOrganService;
import com.yuyou.tas.admin.service.IAuthRoleService;
import com.yuyou.tas.admin.service.IAuthUserRoleRelationService;
import com.yuyou.tas.admin.service.IAuthUserService;
import com.yuyou.tas.admin.vo.req.AuthSubjectSection;
import com.yuyou.tas.service.api.admin.dto.SycnUserUpdateObj;
import com.yuyou.tas.service.api.admin.entity.AuthRole;
import com.yuyou.tas.service.api.admin.entity.AuthUser;
import com.yuyou.tas.service.api.admin.entity.AuthUserRoleRelation;
import com.yuyou.tas.service.api.admin.entity.AuthUserSection;
import com.yuyou.tas.service.api.admin.entity.AuthUserSubject;
import com.yuyou.tas.service.api.lesson.service.BaseDataAPI;
import com.yuyou.tas.service.api.lesson.service.LessonClassAPI;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.config.SystemConfig;
import com.yuyou.tas.util.enums.admin.AuthRoleEnums;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import com.yuyou.tas.util.exception.ResBoolSimpleInfoException;
import com.yuyou.tas.util.tool.DateUtil;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.MD5Util;
import com.yuyou.tas.util.tool.PingYinUtil;
import com.yuyou.tas.util.tool.Sequence;

@Service
public class AuthUserServiceAopImpl  {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());  
	
    @Autowired
    private AuthUserMapper authUserMapper;

    @Autowired
    private AuthUserSubjectMapper authUserSubjectMapper;

    @Autowired
    private AuthUserSectionMapper authUserSectionMapper;

    @Autowired
    private AuthRoleMapper authRoleMapper;

    @Autowired
    private BaseDataAPI baseDataAPI;

    @Autowired
    private AuthUserRoleRelationMapper authUserRoleRelationMapper;

    @Autowired
    private IAuthUserRoleRelationService authUserRoleRelationService;

    @Autowired
    private IAuthOrganService authOrganService;

    @Autowired
    private LessonClassAPI lessonClassAPI;
    
    @Autowired
    private IAuthRoleService authRoleService;
    
    @Autowired
    private IAuthUserService authUserService;
	
    @Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> sycnUserByOId(SycnUserUpdateObj obj) throws Exception {	
						
			AuthUser authUserSycn=authUserMapper.selectByOrgan7OId(obj.getoId(), obj.getAuthOrganizationId());
			
			AuthUser authUser=new AuthUser();
			DefindBeanUtils.copyProperties(obj, authUser);
			authUser.setSpell(PingYinUtil.getFirstPYIndexStr(authUser.getUsername(), true));		
			
			boolean needBindRole=true;
			if(authUserSycn!=null){
				authUser.setId(authUserSycn.getId());
				authUserService.updateByPrimaryKeySelective(authUser);			
			}else{				
				AuthUser checkUni=authUserService.seleteUserByAcc7Organ(obj.getAccount(),obj.getAuthOrganizationId());
				if(checkUni!=null){
					throw new ResBoolSimpleInfoException("account("+obj.getAccount()+")账号已存在");
				}				
				//初始化用户密码
				authUser.setPassword(MD5Util.md5Hex(SystemConfig.INIT_PASSWORD));
				authUser.setSchoolType(AuthUserEnums.schoolType.all.getValue());
				authUserService.insert(authUser);				
			}
			
			if(authUserSycn!=null){
				//变换角色
				if(authUserSycn.getType().intValue()!=authUser.getType().intValue()){				
					//删除原来角色
					int oriRoleType=AuthRoleEnums.getRoleTypeByUserType(authUserSycn.getType());					
					authUserRoleRelationService.deleteByUserRole(authUserSycn.getId(), oriRoleType);
				}else{
					needBindRole=false;
				}
			}
			
			if(needBindRole){
				//绑定新角色
				int roleType=AuthRoleEnums.getRoleTypeByUserType(authUser.getType());						
				AuthRole authRole=authRoleService.selectUniByRoleType(roleType);			
	            AuthUserRoleRelation authUserRoleRelation = new AuthUserRoleRelation();
	            authUserRoleRelation.setId(Sequence.getSequence().nextId());
	            authUserRoleRelation.setAuthUserId(authUser.getId());
	            authUserRoleRelation.setAuthRoleId(Long.valueOf(authRole.getId()));
	            authUserRoleRelation.setCreateTime(DateUtil.now());
	            authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelation);	
			}
           
            //年级科目
			List<AuthSubjectSection> assList=new ArrayList<AuthSubjectSection>();
			List<String> sectionStrList=obj.getSections().stream().map(item->String.valueOf(item)).collect(Collectors.toList());
			String sectionStr=String.join(",", sectionStrList);			
			obj.getSubjects().forEach(item->{
				AuthSubjectSection ass=new AuthSubjectSection(item,sectionStr);				
				assList.add(ass);
			});
			
	        // 删除年级科目，再插入
	        authUserSubjectMapper.deleteByAuthUserId(authUser.getId());
	        authUserSectionMapper.deleteByAuthUserId(authUser.getId());
	        
	     // 添加科目年级
	        for(Long subject:obj.getSubjects()){
	            AuthUserSubject authUserSubject = new AuthUserSubject();
	            authUserSubject.setId(Sequence.getSequence().nextId());
	            authUserSubject.setAuthUser(authUser.getId());
	            authUserSubject.setDataSubject(subject);
	            authUserSubject.setCreateTime(DateUtil.now());
	            authUserSubjectMapper.insert(authUserSubject);
	                        
	            AuthUserSection authUserSection = new AuthUserSection();
	            authUserSection.setId(Sequence.getSequence().nextId());
	            authUserSection.setAuthUser(authUser.getId());
	            authUserSection.setBaseSectionId(String.join(",", sectionStrList));
	            authUserSection.setDataSubject(subject);
	            authUserSection.setCreateTime(DateUtil.now());
	            authUserSectionMapper.insert(authUserSection);   
	        }				

			
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	
	
}
